from PyQt5.QtCore import QThread, pyqtSignal
import logging
from multi_format_frame_processor import MultiFormatFrameProcessor


class MultiFormatFileLoaderThread(QThread):
    """支持多格式的文件加载线程
    
    Signals:
        progress_signal: 发送进度信息，参数为进度值(0-100)、状态描述和详细信息
        finished_signal: 加载完成信号，发送读取的帧数据
        error_signal: 错误信号，发送错误信息
    """
    progress_signal = pyqtSignal(int, str, str)  # 进度值, 状态描述, 详细信息
    finished_signal = pyqtSignal(list)  # 读取完成的帧列表
    error_signal = pyqtSignal(str)  # 错误信息
    
    def __init__(self, file_path: str, frame_format: str):
        """初始化文件加载线程
        
        Args:
            file_path: 文件路径
            frame_format: 帧格式 ('1092', '1024', '896')
        """
        super().__init__()
        self.file_path = file_path
        self.frame_format = frame_format
        self.is_cancelled = False
        self.logger = logging.getLogger('frame_analyzer')
        self.processor = MultiFormatFrameProcessor()
        
    def run(self):
        """线程执行函数"""
        try:
            self.logger.info(f"开始在后台线程中加载文件: {self.file_path}, 格式: {self.frame_format}字节")
            
            def progress_callback(value, status, detail=None):
                if self.is_cancelled:
                    raise Exception("操作已取消")
                self.progress_signal.emit(value, status, detail or "")
            
            # 使用多格式处理器读取文件
            frames = self.processor.read_frames_with_format(
                self.file_path, 
                self.frame_format, 
                progress_callback
            )
            
            if not self.is_cancelled:
                self.logger.info(f"文件加载完成，共读取 {len(frames)} 帧 (格式: {self.frame_format}字节)")
                self.finished_signal.emit(frames)
                
        except Exception as e:
            self.logger.error(f"文件加载线程出错: {str(e)}")
            if str(e) != "操作已取消":
                self.error_signal.emit(str(e))
    
    def cancel(self):
        """取消操作"""
        self.logger.warning("用户取消了文件加载操作")
        self.is_cancelled = True 